"""
questions.py - Question handling for the /question prefix.

Scans public/questions/ for files named q<number>.html.
Handles:
  - /question or /question/list   -> list page
  - /question/random              -> redirect to random question
  - /question/<number>            -> serve q<number>.html
"""

import os
import random
import config

QUESTIONS_DIR = os.path.join(config.PUBLIC_DIR, 'questions')


def _get_question_numbers():
    """Return a sorted list of question numbers found in QUESTIONS_DIR."""
    numbers = []
    if not os.path.isdir(QUESTIONS_DIR):
        return numbers
    for filename in os.listdir(QUESTIONS_DIR):
        if filename.startswith('q') and filename.endswith('.html'):
            try:
                num = int(filename[1:-5])
                numbers.append(num)
            except ValueError:
                pass
    return sorted(numbers)


def handle_question(handler, route_path):
    """
    Main entry point for /question/* routes.
    Delegates to the appropriate sub‑handler.
    """
    # Extract the part after '/question'
    sub_path = route_path[len('/question'):]  # e.g., '', '/', '/list', '/random', '/3'

    # Normalise: strip leading/trailing slashes
    sub_path = sub_path.strip('/')

    # ---- List: /question, /question/, /question/list ----
    if sub_path in ('', 'list'):
        _list_page(handler)
        return

    # ---- Random: /question/random ----
    if sub_path == 'random':
        _random_redirect(handler)
        return

    # ---- Specific question: /question/<number> ----
    if sub_path.isdigit():
        num = int(sub_path)
        _serve_question_file(handler, num)
        return

    # Unknown sub‑path
    handler.send_error(404, 'Question route not found')


def _list_page(handler):
    """Serve the question listing page."""
    numbers = _get_question_numbers()
    body_parts = [
        '<!DOCTYPE html>',
        '<html>',
        '<head><title>Questions</title></head>',
        '<body>',
        '<h1>MCQ Questions</h1>',
    ]
    if not numbers:
        body_parts.append('<p>No questions found.</p>')
    else:
        body_parts.append('<ul>')
        for n in numbers:
            body_parts.append(f'<li><a href="/question/{n}">Question {n}</a></li>')
        body_parts.append('</ul>')
        body_parts.append('<p><a href="/question/random">Random question</a></p>')
    body_parts.append('<p><a href="/">Home</a></p>')
    body_parts.append('<p><a href="/logout">Logout</a></p>')
    body_parts.append('</body></html>')

    body = '\n'.join(body_parts)
    content = body.encode('utf-8')

    handler.send_response(200)
    handler.send_header('Content-Type', 'text/html; charset=utf-8')
    handler.send_header('Content-Length', len(content))
    _maybe_set_cookie(handler)
    handler.end_headers()
    handler.wfile.write(content)


def _random_redirect(handler):
    """Redirect to a randomly chosen /question/<number>."""
    numbers = _get_question_numbers()
    if not numbers:
        handler.send_error(404, 'No questions available')
        return
    n = random.choice(numbers)
    handler.send_response(302)
    handler.send_header('Location', f'/question/{n}')
    _maybe_set_cookie(handler)
    handler.end_headers()


def _serve_question_file(handler, number):
    """Serve the file public/questions/q<number>.html."""
    filename = f'q{number}.html'
    file_path = os.path.join(QUESTIONS_DIR, filename)

    # Security: ensure path stays inside QUESTIONS_DIR
    abs_questions = os.path.abspath(QUESTIONS_DIR)
    abs_file = os.path.abspath(file_path)
    if not abs_file.startswith(abs_questions):
        handler.send_error(403, 'Forbidden')
        return

    if not os.path.isfile(abs_file):
        handler.send_error(404, 'Question not found')
        return

    try:
        with open(abs_file, 'rb') as f:
            content = f.read()
    except Exception:
        handler.send_error(500, 'Internal Server Error')
        return

    handler.send_response(200)
    handler.send_header('Content-Type', 'text/html; charset=utf-8')
    handler.send_header('Content-Length', len(content))
    _maybe_set_cookie(handler)
    handler.end_headers()
    handler.wfile.write(content)


def _maybe_set_cookie(handler):
    """Set the session cookie if needed (avoids duplicating imports)."""
    import session
    if hasattr(handler, '_new_sid') and handler._new_sid:
        session.set_session_cookie(handler)